package ml.tewas.generator;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.imageio.ImageIO;

import ml.tewas.commondata.BoardCell;
import ml.tewas.commondata.ForceEnum;
import ml.tewas.commondata.ForceStruct;
import ml.tewas.util.Utilities;

public class ForceGenerator {

	private static final String IMAGE_ROOT = "/ml/tewas/images/";

	private int totalWeapon;

	private Random randomNumberGenerator;
	
	private List<BoardCell> previousPositions = new ArrayList<BoardCell>();

	public ForceGenerator(int totalWeapon) {
		this.totalWeapon = totalWeapon;
		randomNumberGenerator = new Random();
	}

	public List<ForceStruct> generateForces(int numberOfAgents, boolean isTraining) {

		List<ForceStruct> forceList = new ArrayList<ForceStruct>();

		forceList.add(getUnArmedForce(isTraining));

		for (int i = 0; i < numberOfAgents; i++) {

			BoardCell position = getPosition();
			BufferedImage image = getImage(ForceEnum.ARMEDAGENT);
			int weaponCount = getWeaponCount();
			ForceStruct temp = new ForceStruct(i, position,
					ForceEnum.ARMEDAGENT, weaponCount, image, isTraining);
			forceList.add(temp);
		}
		return forceList;
	}

	private int getWeaponCount() {
		return totalWeapon/2;
	}

	private ForceStruct getUnArmedForce(boolean isTraining) {
		return new ForceStruct(Utilities.UNARMED_AGENT_ID, getPosition(),
				ForceEnum.UNARMED, Utilities.NO_WEAPON, getImage(ForceEnum.UNARMED),isTraining);
	}

	private BoardCell getPosition() {
		int x;
		int y;
		while (true) {
			x = randomNumberGenerator.nextInt(16);
			y = randomNumberGenerator.nextInt(16);
			if (Utilities.inSafeZone(x, y)) {
				BoardCell temp = new BoardCell(x, y);
				if (!previouslyTaken(x, y)) {
					previousPositions.add(temp);
					return temp;
				}
			}
		}
	}

	private boolean previouslyTaken(int x, int y) {

		for (BoardCell temp : previousPositions) {
			if (temp.getCellXPosition() == x && temp.getCellYPosition() == y)
				return true;
		}
		return false;
	}

	private BufferedImage getImage(ForceEnum force) {
		String path = IMAGE_ROOT + force.name() + ".jpg";
		URL imgURL = getClass().getResource(path);
		BufferedImage img = null;
		try {
			img = ImageIO.read(imgURL);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return img;
	}
}
